package com.example.tcp.server.example;

import com.example.tcp.server.Client;
import com.example.tcp.server.Frame;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AsciiString;

import java.util.function.Function;


public class ExampleFrame extends Frame {

    public ExampleFrame(ByteBuf data) {
        super(data);
    }

    @Override
    public Client getClient(ChannelHandlerContext ctx) {

        if(this.content().getUnsignedShort(0) != 0x5555) {
            return null;
        }

        AsciiString deviceId = new AsciiString(ByteBufUtil.getBytes(this.content(), 4, 15));
        return Client.getOrCreateClient(deviceId, ctx.channel(), new Function<AsciiString, Client>() {
            @Override
            public Client apply(AsciiString key) {
                return new ExampleClient(key, ctx.channel());
            }
        });
    }
}
